package edu.yctc.origin.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import edu.yctc.origin.constant.ResultCode;
import edu.yctc.origin.controller.verification.VerificationCodeHolder;
import edu.yctc.origin.dao.UserDAO;
import edu.yctc.origin.entity.ResultDO;
import edu.yctc.origin.service.MessageIService;
import edu.yctc.origin.warpper.MailWarpper;

/**
 * 邮箱业务接口实现
 * 
 * @author 赵宜珺
 *
 */
@ComponentScan({"edu.yctc.origin.dao"})
@Service("messageService")
public class MessageServiceImpl implements MessageIService {

    private final static Logger LOG = LoggerFactory.getLogger("serviceLog");

    /** 邮件标题 */
    private final static String MAIL_TITLE = "邮箱验证码";
    /** 邮件验证码模板前缀 */
    private final static String MAIL_PREFIX = "您的验证码是";
    /** 邮件验证码模板后缀 */
    private final static String MAIL_SUBFIX = "。如非本人操作，请忽略本短信。";

    @Resource
    private UserDAO userDAO;

    @Autowired
    private MailWarpper mailWarpper;

    @Override
    public ResultDO<Void> sendVerificationCodeMail(String mail) {
        try {
            if (StringUtils.isBlank(mail)) {
                LOG.error("send mail fail, mail is null, mail={}", mail);
                return new ResultDO<>(false, ResultCode.NO_SUCH_MAIL, ResultCode.MSG_NO_SUCH_MAIL);
            }
            // 发邮件
            String verificationCode = VerificationCodeHolder.getMailVerificationCode(mail);
            mailWarpper.sendMail(mail, MAIL_TITLE, MAIL_PREFIX + verificationCode + MAIL_SUBFIX);
            LOG.info("send mail success, mail={}", mail);
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } catch (Exception e) {
            LOG.error("send mail error, mail={}", mail, e);
            return new ResultDO<>(false, ResultCode.ERROR_SYSTEM_EXCEPTION, ResultCode.MSG_ERROR_SYSTEM_EXCEPTION);
        }
    }

}
